const path = require('path')
const glob = require('glob');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const PurgeCSSPlugin = require('purgecss-webpack-plugin')
const isDev = process.env.NODE_ENV

const PATHS = {
    src: path.join(__dirname, 'src')
}
module.exports = {
    mode: 'production',
    entry: './src/index.js',
    output: {
        filename: 'js/[name].[contenthash].js',
        path: path.resolve(__dirname + '/dist'),
        assetModuleFilename: 'imgs/[name].[contenthash][ext][query]'
        // publicPath: '../dist/'
    },
    resolve: {
        alias: {
            "@": path.resolve(__dirname, "src")
        }
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                use: {
                    loader: "babel-loader",
                },
            },
            {
                test: /\.css$/,
                use: [{
                    loader: isDev ? 'style-loader' : MiniCssExtractPlugin.loader
                }, 'css-loader', {
                    loader: "postcss-loader",
                    // options: {
                    //     postcssOptions: {
                    //         plugins: [
                    //             require("postcss-preset-env")(),

                    //         ]
                    //     }
                    // }
                }
                ]
            },
            {
                test: /\.scss$/,
                use: ['style-loader', 'css-loader', "postcss-loader", 'sass-loader'
                ]
            },
            {
                test: /\.(png|jpg|gif|jpeg|webp|svg|eot|ttf|woff|woff2)$/,
                exclude: /node_modules/,
                type: 'asset/resource'
            },
            {
                test: /\.html$/,
                loader: "html-loader",
            }
        ]
    },
    plugins: [
        new HtmlWebpackPlugin({
            filename: 'index.html',
            template: 'index.html',
            inject: 'body'
        }),
        new CleanWebpackPlugin(),
        new MiniCssExtractPlugin({
            filename: "css/[name].[contenthash].css",
        }),
        new CssMinimizerPlugin(),
        new PurgeCSSPlugin({
            paths: glob.sync(`${PATHS.src}/**/*`, { nodir: true }),
            safelist: ['body']
        })
    ]
}